import { Component, OnInit } from '@angular/core';
import { MessageService } from 'primeng/api';
import { BaseComponent, Utils } from 'iisp-ng';

import { DataIEService } from '../dataie.service.js';
import { DataExportRequest, TableInfo, TableTemplate } from '../model.js';

declare var contextPath: string, fileDownloadRoot: string;
declare function setTableBodyHeight(): void;

@Component({
	selector: 'data-export',
	templateUrl: "./export.component.html",
	providers: [DataIEService]
})
export class DataExportComponent extends BaseComponent implements OnInit {
	tableList: TableInfo[];
	selectedTable: TableInfo;
	dataExport: DataExportRequest;
	tableTemplates: TableTemplate[];
	selectedTemplate: TableTemplate;
	constructor(private dataieService: DataIEService, messageService: MessageService) { 
	    super(messageService);
	}

	ngOnInit(): void {
		this.getTableList();
	}
//	ngAfterViewInit(): void {
//		setTableBodyHeight();
//	}
	getTableList(): void {
		this.dataieService.getTableList().subscribe(rst => this.tableList = rst, err => this.handleError(err));
	}

	getDataExportRequest(): void {
		this.dataieService.getTableTemplateList(this.selectedTable.code).subscribe(rst => {
			this.tableTemplates = rst;
			if (rst && rst.length > 0) {
				rst[0].isSelected = true;
				this.selectedTemplate = rst[0];
			}
			this.dataieService.getDataExportRequest(this.selectedTable.code).subscribe(rst => {
				this.dataExport = rst;
				this.dataExport.useTemplate = (this.selectedTemplate != null);
			}, err => this.handleError(err));
		}, err => this.handleError(err));
	}

	exportData(): void {
		if (this.selectedTemplate) {
			this.dataExport.templateId = this.selectedTemplate.id;
		}
		this.dataieService.exportData(this.dataExport).subscribe(rst => {
			window.open(fileDownloadRoot + rst.value);
		}, err => this.handleError(err));
	}

	selectTemplate(tmpl: TableTemplate) {
		for (let t of this.tableTemplates) {
			t.isSelected = null;
		}
		tmpl.isSelected = true;
		this.selectedTemplate = tmpl;
	}

	onSelectTable(tbl: TableInfo): void {
		this.selectedTable = tbl;
		this.selectedTemplate = null;
		this.dataExport = null;
		this.getDataExportRequest();
		for (let tb of this.tableList) {
			tb.isSelected = false;
		}
		this.selectedTable.isSelected = true;
	}
}